

//工具栏上的所有的功能按钮和下拉框，可以在new编辑器的实例时选择自己需要的重新定义
window.UEDITOR_HOME_URL = __root_dir__+"/common/plugins/Ueditor/";
var ueditor_toolbars = [[
    'fullscreen', 'source', '|', 'undo', 'redo', '|',
    'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', '|',
    'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
    'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
    'directionalityltr', 'directionalityrtl', 'indent', '|',
    'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
    'link', 'unlink', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
    'simpleupload', 'insertimage', 'emotion', 'insertvideo', 'attachment', 'map', 'insertframe', 'insertcode', '|',
    'horizontal', 'spechars', '|',
    'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
    'preview', 'searchreplace', 'drafts'
]];

$(function(){
    try{
        GetUploadInst(); //上传图片
    }catch(e){
    }
});

// 批量删除提交
function batch_del(obj, name){
    var deltype = $(obj).attr('data-deltype');
    if ('pseudo' == deltype) {
        layer.msg('确定操作？', {
            btnAlign: 'c'
            ,time: 0
            ,btn: ['直接删除', '放入回收站', '取消']
            ,yes: function(index, layero){
                batch_del_pseudo(obj, name, 1);
                return false;
            }
            ,btn2: function(index, layero){
                batch_del_pseudo(obj, name, 2);
                return false;
            }
            ,btn3: function(index, layero){
                layer.close(index);
            }
        });
    } else {
        layer.msg('确定操作？', {
            btnAlign: 'c'
            ,time: 0
            ,btn: ['直接删除', '取消']
            ,yes: function(index, layero){
                batch_del_pseudo(obj, name, 2);
                return false;
            }
            ,btn2: function(index, layero){
                layer.close(index);
            }
        });
    }
}
// 批量移动操作
function batch_move(obj, name) {
    // 删除按钮
    layer.confirm('确认批量移动？', {
        btn: ['确定', '取消'] //按钮
    }, function (index) {
        layer.load(2);
        $.ajax({
            type: "POST",
            url: $(obj).attr('data-url'),
            data: {move_id:name},
            dataType: 'json',
            success: function (data) {
                layer.closeAll();
                if(data.status == 1){
                    layer.msg(data.msg, {icon: 1, time:1000}, function(){
                        window.location.reload();
                    });
                }else{
                    layer.msg(data.msg, {icon: 2,time:1000});
                }
            },
            error:function(){
                layer.closeAll();
                layer.msg("未知错误，操作中断！", {icon: 2,time:1000});
            }
        });
    }, function (index) {
        layer.closeAll(index);
    });
}
// 批量删除-针对临时存放在回收站的数据
function batch_del_pseudo(obj, a, del_type){
    var url = $(obj).attr('data-url');
    if (1 == del_type) {
        layer.load(2);
        $.ajax({
            type: "POST",
            url: url,
            data: {del_id:a, thorough:1},
            dataType: 'json',
            success: function (res) {
                layer.closeAll();
                if(res.code == 1){
                    layer.msg(res.msg, {icon: 1, time:1000}, function(){
                        window.location.reload();
                    });
                }else{
                    layer.msg(res.msg, {icon: 2,time:1000});
                }
            },
            error:function(){
                layer.closeAll();
                layer.msg("未知错误，操作中断！", {icon: 2,time:1000});
            }
        });
    } 
    else if (2 == del_type) 
    {
        layer.load(2);
        $.ajax({
            type: "POST",
            url: url,
            data: {del_id:a},
            dataType: 'json',
            success: function (res) {
                layer.closeAll();
                if(res.code == 1){
                    layer.msg(res.msg, {icon: 1, time:1000}, function(){
                        window.location.reload();
                    });
                }else{
                    layer.msg(res.msg, {icon: 2,time:1000});
                }
            },
            error:function(){
                layer.closeAll();
                layer.msg("未知错误，操作中断！", {icon: 2,time:1000});
            }
        });
    }
    else{
        layer.load(2);
        $.ajax({
            type: "POST",
            url: url,
            data: {del_id:a},
            dataType: 'json',
            success: function (res) {
                layer.closeAll();
                if(res.code == 1){
                    layer.msg(res.msg, {icon: 1, time:1000}, function(){
                        window.location.reload();
                    });
                }else{
                    layer.msg(res.msg, {icon: 2,time:1000});
                }
            },
            error:function(){
                layer.closeAll();
                layer.msg("未知错误，操作中断！", {icon: 2,time:1000});
            }
        });
    }
}
// 单个删除
function delfun(obj) {
    var url = $(obj).attr('data-url');
    var deltype = $(obj).attr('data-deltype');
    if ('pseudo' == deltype) {
        layer.msg('确定操作？', {
            btnAlign: 'c'
            ,time: 0
            ,btn: ['直接删除', '放入回收站', '取消']
            ,yes: function(index, layero){
                delfun_pseudo(obj, 1);
                return false;
            }
            ,btn2: function(index, layero){
                delfun_pseudo(obj, 2);
                return false;
            }
            ,btn3: function(index, layero){
                layer.close(index);
            }
        });
    } else {
        layer.msg('确定操作？', {
            btnAlign: 'c'
            ,time: 0
            ,btn: ['直接删除', '取消']
            ,yes: function(index, layero){
                delfun_pseudo(obj, 2);
                return false;
            }
            ,btn2: function(index, layero){
                layer.close(index);
            }
        });
    }
}
// 单个删除 - 执行操作
function delfun_pseudo(obj, del_type) {
    var url = $(obj).attr('data-url');
    if (1 == del_type) {
        layer.load(2);
        $.ajax({
            type : 'POST',
            url : url,
            data : {del_id:$(obj).attr('data-id'), thorough:1},
            dataType : 'json',
            success : function(res){
                layer.closeAll();
                if(res.code == 1){
                    layer.msg(res.msg, {icon: 1, time:1000}, function(){
                        window.location.reload();
                    });
                }else{
                    layer.msg(res.msg, {icon: 2,time:1000});
                }
            },
            error:function(){
                layer.closeAll();
                layer.msg("未知错误，操作中断！", {icon: 2,time:1000});
            }
        })
    }else if (2 == del_type){
        layer.load(2);
        $.ajax({
            type : 'POST',
            url : url,
            data : {del_id:$(obj).attr('data-id')},
            dataType : 'json',
            success : function(res){
                layer.closeAll();
                if(res.code == 1){
                    layer.msg(res.msg, {icon: 1, time:1000}, function(){
                        window.location.reload();
                    });
                }else{
                    layer.msg(res.msg, {icon: 2,time:1000});
                }
            },
            error:function(){
                layer.closeAll();
                layer.msg("未知错误，操作中断！", {icon: 2,time:1000});
            }
        })
    }
}
//全选
function selectAll(name,obj){
    $('input[name*='+name+']').prop('checked', $(obj).checked);
} 
// 远程/本地上传图片切换
function clickRemote(obj, id){
    if ($(obj).is(':checked')) {
        $('#'+id+'_remote').show();
        $('.div_'+id+'_local').hide();
    } else {
        $('.div_'+id+'_local').show();
        $('#'+id+'_remote').hide();
    }
}
//上传图片 后台专用
function GetUploadInst(){
    var result = typeof layui;
    if ('undefined' == result || undefined == result) {
        return false;
    }
    //单图片上传
    layui.use('upload', function(){
        var upload = layui.upload;
        var load;
        //执行实例
        var uploadInst = upload.render({
            elem: '.test-upload-demoMore', //绑定元素
            url: __admin_dir__+'/system.Ueditor/imageUp', //上传接口
            before: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
                this.data.savepath = this.ey_savepath;
                load = layer.load(); //上传loading
            },
            done: function(res, index, upload){
                layer.close(load); //关闭loading
                var ey_callback = this.ey_callback;
                //如果上传失败
                if(res.state == 'SUCCESS'){
                    if (!ey_callback) {
                        $('#'+this.ey_inputId).val(res.url);
                        $('#img_'+this.ey_inputId).attr('src',res.url);
                        return;
                    } else {
                        eval('window.'+ey_callback+'(res)');
                        return;
                    }
                } else {
                    return layer.msg(res.state, {icon:5, time: 1500});
                }
                //上传成功
            },
            error: function(){
                layer.close(load); //关闭loading
            }
        });
    });
    //多图片上传
    layui.use('upload', function(){
        var upload = layui.upload;
        //执行实例
        var uploadInst = upload.render({
            elem: '.multi-upload-demoMore' //绑定元素
            ,acceptMime:'image/*'
            ,multiple:true
            ,auto: false
            ,url: __admin_dir__+'/system.Ueditor/imageUp' //上传接口
            ,choose:function (obj) {        //判断文件是否满足上传条件
                if (this.ey_callbefore){
                    if (!eval('window.'+this.ey_callbefore)){
                        return false;
                    }
                }
                obj.preview(function(index, file, result){
                    obj.upload(index, file); //对上传失败的单个文件重新上传，一般在某个事件中使用
                });
            }
            ,before: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
                this.data.savepath = this.ey_savepath;
                layer.load(); //上传loading
            }
            ,done: function(res, index, upload){
                layer.closeAll('loading'); //关闭loading
                var ey_callback = this.ey_callback;
                //如果上传失败
                if(res.state == 'SUCCESS'){
                    if (!ey_callback) {
                        $('#'+this.ey_inputId).val(res.url);
                        return;
                    } else {
                        eval('window.'+ey_callback+'(res)');
                        return;
                    }
                } else {
                    return layer.msg(res.state, {icon:2, time: 1500});
                }
                //上传成功
            }
            ,error: function(){
                layer.closeAll('loading'); //关闭loading
            }
        });
    });
}
//查看大图
function BigImages(imgpath){
    var max_width = 650;
    var max_height = 450;
    var img = "<img src='"+imgpath+"'/>";
    $(img).load(function() {
        width  = this.width;
        height = this.height;
        if (width > max_width) {
            width = max_width;
            width += 'px';
        }else if (width > height) {
            if (width > max_width) {
                width = max_width;
            }
            width += 'px';
        } else {
            width = 'auto';
        }
        if (height > max_height) {
            height = max_height;
            height += 'px';
        }else if (width < height) {
            if (height > max_height) {
                height = max_height;
            }
            height += 'px';
        } else {
            height = 'auto';
        }
        var content = "<img style='width:"+width+";height:"+height+";' src="+imgpath+">";
        parent.layer.open({
            id:'pcfid',
            type: 1,
            title: false,
            closeBtn: true,
            shadeClose:true,
            area: [width, height],
            skin: 'layui-layer-nobg', //没有背景色
            content: content
        });
    });
}
//清空上传缩略图的图片显示
function DelImages(obj){
    var inputid = $(obj).data('inputid');
    try{
        $("#"+inputid).val('');
        $("input[name='"+inputid+"']").val('');
    }catch(e){
        console.log(e);
    }
    $('#img_'+inputid).attr('src', '/common/images/not_adv.jpg');
}
/*
 * 图库 后台专用
 * @access  public
 * @num int 一次上传图片张图
 * @inputId string 上传成功后返回路径插入指定ID元素内
 * @path  string 指定上传保存文件夹,默认存在public/uploads/temp/目录
 * @callback string  回调函数(单张图片返回保存路径字符串，多张则为路径数组 )
 */
var layer_GetPictureFolder;
function GetPictureFolder(num,inputId,callback)
{
    if (layer_GetPictureFolder){
        layer.close(layer_GetPictureFolder);
    }
    if (!callback) {
        callback = '';
    }
    var width = '85%';
    var height = '85%';
    var upurl = __admin_dir__+'/system.uploadify/picture_folder/num/'+num+'/inputId/'+inputId+'/func/'+callback;
    layer_GetPictureFolder = layer.open({
        type: 2,
        title: '图库管理',
        shadeClose: false,
        shade: 0.3,
        maxmin: true,//开启最大化最小化按钮
        area: [width, height],
        content: upurl
    });
}
//修改指定表的指定字段值 包括有按钮点击切换是否 或者 排序 或者输入框文字
function changeTableVal(table,id_name,id_value,field,obj,pcfurl,ctl_act){
    if(obj){
        var value = $(obj).val();//其他输入框操作            
    }
    var url = pcfurl;
    $.ajax({
        type: 'POST',
        url: url,
        data: {table:table,id_name:id_name,id_value:id_value,field:field,value:value,act:ctl_act},
        dataType: 'json',
        success: function(res){
            if (res.status) {
                if('switch' != $(obj).attr('lay-skin')){
                    layer.msg(res.msg, {icon: 1, time:1000});
                }
                if (1 == res.data.refresh) {
                    window.location.reload();
                }
            } else {
                layer.msg(res.msg, {icon: 2, time:1000}, function(){
                    window.location.reload();
                });  
            }
        }
    })
}

//百度提交
function baiduTableVal(pcfurl,tsurl){
    $.ajax({type: 'POST',url: tsurl,data: {baiduurl:pcfurl},dataType: 'json'})
}



/*
 * 图库 后台专用(存在前置判断)
 * @access  public
 * @num int 一次上传图片张图
 * @inputId string 上传成功后返回路径插入指定ID元素内
 * @path  string 指定上传保存文件夹,默认存在public/upload/temp/目录
 * @callback string  回调函数(单张图片返回保存路径字符串，多张则为路径数组 )
 */
function GetBeforePictureFolder(num,inputId,callback,callbeofre)
{
    if (layer_GetPictureFolder){
        layer.close(layer_GetPictureFolder);
    }
    if (callbeofre){
        if (!eval('window.'+callbeofre)){
            return false;
        }
    }
    if (!callback) {
        callback = '';
    }
    var width = '85%';
    var height = '85%';

    var upurl = __admin_dir__+'/system.uploadify/picture_folder/num/'+num+'/inputId/'+inputId+'/func/'+callback;
    layer_GetPictureFolder = layer.open({
        type: 2,
        title: '图库管理',
        shadeClose: false,
        shade: 0.3,
        maxmin: true, //开启最大化最小化按钮
        area: [width, height],
        content: upurl
    });
}
/*
 * 上传图片 在弹出窗里的上传图片
 * @access  public
 * @null int 一次上传图片张图
 * @elementid string 上传成功后返回路径插入指定ID元素内
 * @path  string 指定上传保存文件夹,默认存在public/upload/temp/目录
 * @callback string  回调函数(单张图片返回保存路径字符串，多张则为路径数组 )
 */
var layer_GetUploadifyFrame;
function GetUploadifyFrame(num,elementid,path,callback,url)
{
    if (layer_GetUploadifyFrame){
        layer.close(layer_GetUploadifyFrame);
    } 
    if (num > 0) {
        if (url.indexOf('?') > -1) {
            url += '&';
        } else {
            url += '?';
        }

        var upurl = url + 'num='+num+'&input='+elementid+'&path='+path+'&func='+callback;
        layer_GetUploadifyFrame = layer.open({
            type: 2,
            title: '上传图片',
            shadeClose: false,
            shade: 0.3,
            maxmin: true, //开启最大化最小化按钮
            area: ['85%', '85%'],
            content: upurl
         });
    } else {
        layer.alert('允许上传0张图片', {icon:2, title:false});
        return false;
    }
}
// post提交之前，切换编辑器从【源代码】到【设计】视图
function ueditorHandle()
{
    try {
        var funcStr = "";
        $('textarea[class*="ckeditor"]').each(function(index, item){
            var func = $(item).data('func');
            if (undefined != func && func) {
                funcStr += func+"();";
            }
        });
        eval(funcStr);
    }catch(e){}
}
// 封装的加载层
function layer_loading(msg){
    ueditorHandle(); // post提交之前，切换编辑器从【源代码】到【设计】视图
    if (!msg || undefined == msg) {
        //loading层
        var loading = layer.load(3, {
            shade: [0.1] //0.1透明度的白色背景
        });
    } else {
        var loading = layer.msg(
        msg+'...&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;请勿刷新页面', 
        {
            icon: 1,
            time: 3600000, //1小时后后自动关闭
            shade: [0.2] //0.1透明度的白色背景
        });
        //loading层
        var index = layer.load(3, {
            shade: [0.1,'#fff'] //0.1透明度的白色背景
        });
    }
    return loading;
}

//关闭当前弹框
function close_this(){
    var index=parent.layer.getFrameIndex(window.name); //获取当前窗口的name
    parent.layer.close(index);
}